<script lang="ts">
export default {
  name: "DeviceEditDialog"
}
</script>

<!--
 * @Description: 设备编辑对话框
 * @version:
 * @Author:
 * @Date: 2022-10-24 09:10:28
 * @LastEditors:
 * @LastEditTime: 2022-10-24 09:10:28
-->
<template>
  <!-- 对话框 -->
  <el-dialog :close-on-click-modal="false" :model-value="visible" :title="dataState.title" min-width="200px"
             @close="handleCancel">

    <!-- 数据表单 -->
    <el-form ref="dataFormRef" :model="dataState.formData" :rules="dataState.rules" label-width="80px">

      <!-- 编辑框：设备名称 -->
      <el-form-item label="设备名称" prop="deviceName">
        <el-input v-model="dataState.formData.deviceName" :disabled="dataState.type==='update'"/>
      </el-form-item>

      <!-- 下拉框：设备类型 -->
      <el-form-item label="设备厂商" prop="manufacturer">
        <el-select v-model="dataState.formData.manufacturer" placeholder="请选择"
                   @change="handleSelectManufacturer">
          <el-option
            v-for="item in dataState.manufacturerOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>

        <!-- 下拉框：设备类型 -->
        <el-form-item label="设备类型" prop="deviceType">
          <el-select v-model="dataState.formData.deviceType" placeholder="请选择"
                     @change="handleSelectDeviceType">
            <el-option
              v-for="item in dataState.deviceTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

      </el-form-item>

      <!-- 通道类型和通道名称 -->
      <el-form-item label="通道类型" prop="channelType">
        <el-select v-model="dataState.formData.channelType" placeholder="请选择"
                   @change="handleSelectChannelType">
          <el-option
            v-for="item in dataState.channelTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>

        <el-form-item label="通道名称" prop="channelName">
          <el-select v-model="dataState.formData.channelName" placeholder="请选择">
            <el-option
              v-for="item in dataState.channelNameOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form-item>


      <!-- 下拉框：设备类型 -->
      <el-form-item label="可用模板" prop="subsetName">
        <el-select v-model="dataState.formData.subsetName"  placeholder="请选择">
          <el-option
            v-for="item in dataState.subsetNameOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>

        <el-form-item label="填入参数" prop="subsetName">
          <el-button :icon="Download"  circle plain type="success"  :disabled="dataState.formData.subsetName === ''"
                     @click="handleDeviceParam"></el-button>
        </el-form-item>
      </el-form-item>



      <!-- 下拉框：配置参数 -->
      <el-form-item label="配置参数" prop="deviceParamJson">
        <el-input v-model="dataState.formData.deviceParamJson" :autosize="{ minRows: 1, maxRows: 100 }" type="textarea"/>
      </el-form-item>

      <!-- 下拉框：配置参数 -->
      <el-form-item label="扩展参数" prop="extendParamJson">
        <el-input v-model="dataState.formData.extendParamJson" :autosize="{ minRows: 1, maxRows: 100 }" type="textarea"/>
      </el-form-item>

    </el-form>

    <!-- 脚部：确认/取消按钮-->
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
        <el-button @click="handleCancel">取 消</el-button>
      </div>
    </template>

  </el-dialog>
</template>

<script lang="ts" setup>
import {nextTick, onMounted, reactive, ref} from "vue";

import {Download} from '@element-plus/icons-vue';
import {ElForm, ElMessage} from "element-plus";
import {DeviceItem} from "@/api/device/device/types";
import {listChannelEntityList} from "@/api/channel";
import {listOption2List, listOptionList} from "@/api/option";
import {listDeviceTemplateEntities, listDeviceTemplateOptions} from "@/api/repo/comp/local";

const props = defineProps(['visible']);
const emit = defineEmits(['create', 'update', 'cancel']); //注意：这个是父组件<dict-type-edit>标签上的@close
const dataFormRef = ref(ElForm); // 属性名必须和元素的ref属性值一致

/**
 * 对外声明接口：父页面可以调用它
 */
defineExpose({initEditData});

// 数据状态：定义
let dataState = reactive({
  // 类型：create/update
  type: 'create',
  // 标题
  title: '添加设备',
  // 表单数据
  formData: {
    id: undefined,
    manufacturer: '',
    deviceType: '',
    channelName: '',
    channelType: '',
    deviceName: '',
    operateTemplate: '',
    subsetName: '',
    deviceParam: {},
    deviceParamJson: '{}',
    extendParam: {},
    extendParamJson: '{}',
  } as any,

  // 厂商类型选项
  manufacturerOptions: [] as OptionType[],
  // 设备类型选项
  deviceTypeOptions: [] as OptionType[],
  // 设备模板的子集
  subsetNameOptions: [] as OptionType[],
  // 通道类型选项
  channelTypeOptions: [] as OptionType[],
  // 通道名称选项
  channelNameOptions: [] as OptionType[],

  // 对话框的各控件输入规则
  rules: {
    deviceName: [{required: true, message: '设备名称不能为空', trigger: 'blur'}],
    manufacturer: [{required: true, message: '设备参数不能为空', trigger: 'blur'}],
    deviceType: [{required: true, message: '设备类型不能为空', trigger: 'blur'}],
    channelName: [{required: true, message: '通道名称不能为空', trigger: 'blur'}],
    channelType: [{required: true, message: '通道类型不能为空', trigger: 'blur'}],
    deviceParamJson: [{required: true, message: '设备参数不能为空', trigger: 'blur'}],
    extendParamJson: [{required: true, message: '扩展参数不能为空', trigger: 'blur'}],
  },
});

async function handleSelectManufacturer(value: any) {
  await listOption2List("OperateEntity", "manufacturer", value, 'deviceType').then(({data}) => {
    dataState.deviceTypeOptions = data;
    if (dataState.deviceTypeOptions.length > 0){
      dataState.formData.deviceType = dataState.deviceTypeOptions[0].value;

      listSubsetNameOptions();
    }
  });
}

async function handleSelectDeviceType(value: any) {
  listSubsetNameOptions();
}

async function listSubsetNameOptions() {
  let queryParams = {
    manufacturer: dataState.formData.manufacturer,
    deviceType: dataState.formData.deviceType,
    templateType: 'device-param',
    field: 'subsetName',
  };

  listDeviceTemplateOptions(queryParams).then(({data}) => {
    dataState.subsetNameOptions = data;
    dataState.formData.subsetName = '';
    if (dataState.subsetNameOptions.length > 0){
      dataState.formData.subsetName = dataState.subsetNameOptions[0].value;
    }
  });
}

async function handleDeviceParam(value: any) {
  let queryParams = {
    manufacturer: dataState.formData.manufacturer,
    deviceType: dataState.formData.deviceType,
    subsetName: dataState.formData.subsetName,
    templateType: 'device-param',
  };
  listDeviceTemplateEntities(queryParams).then(({data}) => {
    if (data.length == 0){
      return;
    }
    dataState.formData.deviceParamJson = JSON.stringify( data[0].templateParam, null, 5);
  });
}

/**
 * 响应通道类型的选择：联动通道类型和通道名称
 * @taskParam value
 */
function handleSelectChannelType(value: any) {
  // 查询指定通道类型的通道实体
  listChannelEntityList({channelType: value}).then(({data}) => {
    // 向后台查询数据，并转换数据结构位option
    const options = [] as OptionType[];
    for (let i = 0; i < data.length; i++) {
      const option = {value: data[i].channelName, label: data[i].channelName} as OptionType;
      options.push(option);
    }

    // 将option保存到通道列表选项的存储空间
    dataState.channelNameOptions = options;

    //设置缺省的通道选择
    dataState.formData.channelName = options[0].value;
  });
}

/**
 * 取消
 */
function handleCancel() {
  //执行调用<device-edit-dialog @cancel="cancelEdit">
  emit('cancel', "子组件传给父组件的值");
}

/**
 * 确认：新增/修改实体
 */
function handleSubmit() {
  if (dataState.formData.deviceName === '') {
    ElMessage.info('设备名称不能为空');
    return;
  }

  try {
    if (dataState.formData.deviceParamJson === undefined) {
      ElMessage.info('配置参数的格式，不是合法的JSON格式!');
      return;
    }

    dataState.formData.deviceParam = JSON.parse(dataState.formData.deviceParamJson);
  } catch (e) {
    ElMessage.info('配置参数的格式，不是合法的JSON格式!');
    return;
  }

  try {
    if (dataState.formData.extendParamJson === undefined) {
      ElMessage.info('扩展参数的格式，不是合法的JSON格式!');
      return;
    }

    dataState.formData.extendParam = JSON.parse(dataState.formData.extendParamJson);
  } catch (e) {
    ElMessage.info('扩展参数的格式，不是合法的JSON格式!');
    return;
  }

  if (dataState.type === 'create') {
    // 执行调用<device-edit-dialog @create="createEdit">的create
    emit('create', dataState.formData);
  }
  if (dataState.type === 'update') {
    //执行调用<device-edit-dialog @update="updateEdit">
    emit('update', dataState.formData);
  }

}

/**
 * 初始化对话框
 * @taskParam type 对话框类型
 * @taskParam entity 实体
 */
function initEditData(type: string, entity: DeviceItem) {
  if (type === 'create') {
    dataState.type = type;
    dataState.title = '新增设备';

    dataState.formData.id = undefined;
    dataState.formData.channelName = '';
    dataState.formData.channelType = '';
    dataState.formData.deviceName = '';
    dataState.formData.deviceType = '';
    dataState.formData.manufacturer = '';
    dataState.formData.deviceParam = {};
    dataState.formData.deviceParamJson = '{}';
    dataState.formData.extendParam = {};
    dataState.formData.extendParamJson = '{}';

    nextTick(() => {
      dataFormRef.value.resetFields();
    })
    return;
  }

  if (type === 'update') {
    dataState.type = type;
    dataState.title = '修改设备';

    dataState.formData.id = entity.id;
    dataState.formData.channelName = entity.channelName;
    dataState.formData.channelType = entity.channelType;
    dataState.formData.deviceName = entity.deviceName;
    dataState.formData.deviceType = entity.deviceType;
    dataState.formData.manufacturer = entity.manufacturer;
    dataState.formData.deviceParam = entity.deviceParam;
    dataState.formData.deviceParamJson = entity.deviceParamJson;
    dataState.formData.extendParam = entity.extendParam;
    dataState.formData.extendParamJson = entity.extendParamJson;
    dataState.formData.subsetName = '';

    if (entity.manufacturer !== undefined) {
      listOption2List("OperateEntity", "manufacturer", entity.manufacturer as string, 'deviceType').then(({data}) => {
        dataState.deviceTypeOptions = data;
      });
    }

    if (entity.deviceType !== undefined) {
      listSubsetNameOptions();
    }

    if (entity.channelType !==undefined){
      listOption2List("ChannelEntity", "channelType", entity.channelType as string, "channelName").then(({data}) => {
        dataState.channelNameOptions = data;
      });
    }

    return;
  }
}

/**
 * 响应页面安装：页面的初始化工作
 */
onMounted(() => {
  // 查询厂商选项，并保存在存量区
  listOptionList("OperateEntity", "manufacturer").then(({data}) => {
    dataState.manufacturerOptions = data;
  });
  // 查询设备类型选项，并保存在存量区
  listOptionList("OperateEntity", "deviceType").then(({data}) => {
    dataState.deviceTypeOptions = data;
  });
  // 查询通道类型选项，并保存在存量区
  listOptionList("ChannelEntity", "channelType").then(({data}) => {
    dataState.channelTypeOptions = data;
  });
});

</script>
